package ejb;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import dto.CandidateDTO;

import dto.PartyDTO;
import dto.SubscribeDTO;
import model.Candidate;

import model.Party;
import model.Subscribe;
import utils.AbstractBean;
import entitymanagers.SubscribeManager;

@Stateless
@LocalBean
public abstract class SubscribeManagerBean extends AbstractBean<Subscribe> implements SubscribeManager{

	public SubscribeManagerBean() {
		super(Subscribe.class);
	}
	
	@PersistenceContext 
	private EntityManager em;
	@Resource
	private SessionContext context;
	
	
	@Override
	public SubscribeDTO[] getCandidate(CandidateDTO candidate) {
		return null;
		
	}

	

	@Override
	public SubscribeDTO getSubscribeByID(String subscribeID) {
		return convertToDTO(find(subscribeID));
	}

	@Override
	public SubscribeDTO[] getSubscribersForParty(PartyDTO party) {
		try{
			Party p = em.find(Party.class, party.getIdParty());
			return convertToDTO(p.getSubscribes());
			}
		catch(Exception e){
			return new SubscribeDTO[0];
		}
	}

	private SubscribeDTO[] convertToDTO(List<Subscribe> subscribes) {
		SubscribeDTO[] sub = new SubscribeDTO[subscribes.size()];
		int i=0;
		for(Subscribe s: subscribes){
			sub[i++] = convertToDTO(s);
		}
		return sub;
	}



	@Override
	public SubscribeDTO[] getSubscribers() {
		return convertToDTO(findAll());
	}

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}

	@Override
	public void addSubscribe(SubscribeDTO subscribe) {
			Candidate candidate = em.find(Candidate.class, context.getCallerPrincipal().getName());
			Party party = em.find(Party.class, subscribe.getParty().getIdParty());
			Subscribe sub = new Subscribe();
			sub.setCandidate(candidate);
			party.addSubscribe(sub);
			em.merge(subscribe);
			em.flush();
			
			}
	public static SubscribeDTO convertToDTO(Subscribe subscribe) {
		SubscribeDTO subscribeDTO = new SubscribeDTO();
		subscribeDTO.setCandidate(subscribeDTO.getCandidate());
		subscribeDTO.setParty(subscribeDTO.getParty());
		subscribeDTO.setIdSubscribe(subscribeDTO.getIdSubscribe());
		return subscribeDTO;
		
	}
	
}
